package com.leyou.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.config.OSSProperties;
import com.leyou.auth.entity.ClientInfo;
import com.leyou.auth.mapper.ClientInfoMapper;
import com.leyou.auth.service.ClientService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class ClientServiceImpl extends ServiceImpl<ClientInfoMapper, ClientInfo> implements ClientService {

    @Value("${ly.jwt.key}")
    private String key;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 根据提供的clientId、secret查询是否是合法服务
     * @param clientId 服务id
     * @param secret 密钥
     * @return 生成jwt的key
     */
    @Override
    public String getSecretKey(String clientId, String secret) {
        if (StringUtils.isEmpty(clientId) || StringUtils.isEmpty(secret)) {
            throw new LyException(400, "请求参数错误");
        }

        ClientInfo info = query().eq("client_id", clientId).one();
        if (null == info || !passwordEncoder.matches(secret, info.getSecret())) {
            throw new LyException(403, "非法请求，禁止访问");
        }
        return key;
    }
}
